package top.oylan.manager.controller.admin;

import com.alibaba.fastjson.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.oylan.manager.entity.extend.ActionExtend;
import top.oylan.manager.service.ActionService;
import top.oylan.manager.tools.Result;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by A on 2019/2/12.
 */
@Controller
@RequestMapping(value = "/admin/perms")
public class AdminPremiseController {

    @Resource
    ActionService actionService;
    
    /**
     *  菜单
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String index(ModelMap modelMap, @RequestParam(value = "roleId",defaultValue = "0")Integer roleId){


        List<ActionExtend> actionExtends = actionService.selectAllActionsWithAuth(roleId);
        List<ActionExtend> treeList = tree(actionExtends, 0);
        modelMap.addAttribute("perms", treeList);
        return "admin/premise/list";
    }


    /**
     * 保存权限
     */

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public Result save(@RequestParam(value = "ids",defaultValue = "")String ids,
                       @RequestParam(value="roleId",defaultValue="0")Integer roleId
    ){

        Result result = new Result();
        JSONArray idsArr = JSONArray.parseArray(ids);
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<idsArr.size();i++){
           list.add(idsArr.getIntValue(i));
        }

        actionService.deletePermsByRoleId(roleId);
        actionService.savePerm(roleId,list);
        result.setCode((byte) 1);
        return result;
    }

    /**
     * 获取树状结构的权限列表
     * @param data
     * @param pid
     * @return
     */
    private List<ActionExtend> tree(List<ActionExtend> data, Integer pid){

        ArrayList<ActionExtend> treeList = new ArrayList<>();
        for(ActionExtend action:data){
            if(action.getParentId() == pid){
                List<ActionExtend> children = tree(data, action.getId());
                action.setChildren(children);
                treeList.add(action);
            }
        }
        return treeList;
    }
}
